package com.ykefu.assign.netty.http;

import com.alibaba.fastjson.JSONObject;
import com.ykefu.assign.netty.AssignSessionStore;
import com.ykefu.assign.netty.ChannelRelationStore;
import com.ykefu.assign.netty.ChannelStore;
import com.ykefu.assign.netty.ClientSessionStore;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author likai
 * @date 2020/4/9 8:53
 * @email likai@7moor..com
 * @desc
 */
public class WebSocketFrameHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketFrameHandler.class);



    public static void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame,WebSocketServerHandshaker handshaker) {
        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // Echo the frame
            String text = ((TextWebSocketFrame) frame).text();
            LOGGER.info("接受到的消息：{}", text);
            JSONObject jsonObject = JSONObject.parseObject(text);
            String message = jsonObject.getString("message");
            String clientId = jsonObject.getString("clientId");
            //解析消息
            // ：{}
            Channel channel = ctx.channel();
            //判断类型。
            ConcurrentHashMap<String, Channel> channelStore = ChannelStore.getChannelStore();
            for (Map.Entry<String,Channel> entry: channelStore.entrySet()) {
                Channel value = entry.getValue();
                if(value!=ctx.channel()){
                    value.writeAndFlush(new TextWebSocketFrame("["+clientId+"] " + message));
                }
            }
            channel.writeAndFlush(new TextWebSocketFrame("[自己]: " + message));
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
        }
    }
}
